package service

import (
	"bookkeeping-gin/app/common/request"
	"bookkeeping-gin/app/model"
	"bookkeeping-gin/global"
	"bookkeeping-gin/utils"
	"errors"
	"log"
)

type userService struct {
}

var UserService = new(userService)

// Register 注册
func (u *userService) Register(params request.RegisterFormWithPwd) (err error, user model.User) {
	result := global.App.DB.Where("username = ?", params.Username).Select("username").First(&model.User{})
	if result.RowsAffected != 0 {
		err = errors.New("用户名已存在")
		return
	}
	// 密码加密
	pwd := utils.BcryptMake([]byte(params.Password))
	// 生成uid
	userid := utils.CreateUid()
	user = model.User{Username: &params.Username, Password: &pwd, Userid: &userid}
	//result = global.App.DB.Where("phone = ?", params.Phone).Select("phone").First(&model.User{})
	//if result.RowsAffected != 0 {
	//	err = errors.New("手机号已存在")
	//	return
	//}
	err = global.App.DB.Create(&user).Error
	if err != nil {
		log.Println("Register failed err:", err)
		return
	}
	return
}

// Login 登录
func (u *userService) Login(params request.LoginForm) (err error, user *model.User) {
	err = global.App.DB.Where("username = ?", params.Username).First(&user).Error
	if err != nil || !utils.BcryptMakeCheck([]byte(params.Password), *user.Password) {
		log.Println("Login failed err:", err)
		err = errors.New("用户名不存在或密码错误")
		return
	}
	return
}

func (u *userService) GetUserInfoById(id string) (err error, user *model.User) {
	err = global.App.DB.Where("userid = ?", id).First(&user).Error

	if err != nil {
		log.Println("GetUserInfoById failed err:", err)
		err = errors.New("用户不存在")
		return
	}
	return
}
